import config
import logging
import sys
import requests
from meta_redir import meta_redir_url
from time import sleep
from random import uniform


from PIL import Image
from io import StringIO, BytesIO

# Get Image


def get_image(meme):

    if(meme.deadlink):
        return(False)
    if(meme.saved):
        return True

    r_redir = requests.get(config.photo_url_prefix+meme.fbid,
                           headers=config.headers, cookies=config.cookies)
    r_redir.raise_for_status()
    final_url = meta_redir_url(r_redir)

    t = uniform(config.sleeptime/2, 1.5*config.sleeptime)
    logging.debug('Made a request, sleeping ' + str(t) + ' seconds…')
    sleep(t)

    if(final_url is None):
        logging.debug("No redirect: page probably does not exist")
        # logging.debug('Content: '+r.text)
        meme.update(deadlink=True)
        meme.save()
        return False
    else:
        logging.debug('Getting photo at '+final_url)
        r = requests.get(final_url)
        if(r.status_code != 200):
            logging.debug('Failed getting '+photo_url_prefix +
                          meme.fbid+' : HTTP error')
            return False

        elif(r.headers['Content-Type'] != 'image/jpeg'):
            logging.debug('Failed getting '+photo_url_prefix +
                          meme.fbid+' : not an image')
            # logging.debug('Type: '+r.headers['Content-Type'])
            return False
        else:
            tentative_path = "data/db/files/jpg/"+meme.fbid+".jpg"
            logging.debug("trying to save file")
            image = Image.open(BytesIO(r.content))

            image.save(tentative_path)
            meme.update(saved=True, deadlink=False)
            meme.update(path=tentative_path)
            meme.save()
            logging.info('Meme saved at '+tentative_path)
            return True
